package com.shiwaixiangcun.customer.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mobstat.SendStrategyEnum;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.shiwaixiangcun.customer.Common;
import com.shiwaixiangcun.customer.ConfigSps;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.GlobalConfig;
import com.shiwaixiangcun.customer.R;
import com.shiwaixiangcun.customer.base.BaseActivity;
import com.shiwaixiangcun.customer.entity.AvatarBean;
import com.shiwaixiangcun.customer.entity.BackEntity;
import com.shiwaixiangcun.customer.entity.LogoutBean;
import com.shiwaixiangcun.customer.entity.User;
import com.shiwaixiangcun.customer.entity.UserInfoBean;
import com.shiwaixiangcun.customer.glide.ImageDisplayUtil;
import com.shiwaixiangcun.customer.network.NetworkHelper;
import com.shiwaixiangcun.customer.presenter.impl.UserInformationImpl;
import com.shiwaixiangcun.customer.ui.IHouseInformationView;
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut;
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr;
import com.shiwaixiangcun.customer.utils.CompressionImageUtil;
import com.shiwaixiangcun.customer.utils.DateUtil;
import com.shiwaixiangcun.customer.utils.JsonUtil;
import com.shiwaixiangcun.customer.utils.LoginOutUtil;
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil;
import com.shiwaixiangcun.customer.utils.ResUtil;
import com.shiwaixiangcun.customer.utils.SharePreference;
import com.shiwaixiangcun.customer.utils.TimerToTimerUtil;
import com.shiwaixiangcun.customer.utils.Utils;
import com.shiwaixiangcun.customer.utils.WheelPriorityDialogFragment;
import com.shiwaixiangcun.customer.widget.ChangeLightImageView;
import com.shiwaixiangcun.customer.widget.PhotoAlbumDialog;
import com.shiwaixiangcun.customer.widget.RoundImageView;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;

/**
 * 个人信息页面
 *
 * @author Administrator
 */
public class InformationActivity extends BaseActivity implements View.OnClickListener, IHouseInformationView {

    private static final int MSG_CODE = 1001;
    private final int RESULT_CODE = 1;
    private final int SAVE_CODE = 1010;
    private ChangeLightImageView backLeft;
    private TextView tvPageName;
    private RoundImageView ivHeadImage;
    private TextView tvInformationName;
    private TextView tvInformationNv;
    private TextView tvInformationOld;
    private TextView tvInformationPhone;
    private Button btnLoginOut;
    private RelativeLayout rlInformationName;
    private UserInformationImpl userInformation;
    private RelativeLayout rlHeadImage;
    private PhotoAlbumDialog selfDialog;
    private Bitmap bitmap1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //接收并处理消息
            if (msg.what == MSG_CODE) {
                //UI更新
                ivHeadImage.setImageBitmap(bitmap1);
            }

        }

    };
    private RelativeLayout rlGender;
    private Dialog dateDialog;
    private RelativeLayout rlDataDialog;
    private String strTrim;
    private String strSex = "";
    private NetworkHelper mNetworkHelper;

    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information);
        //        百度统计
        StatService.setLogSenderDelayed(10);
        StatService.setSendLogStrategy(this, SendStrategyEnum.APP_START, 1, false);
        StatService.setSessionTimeOut(30);

        mNetworkHelper = new NetworkHelper(this, getSupportFragmentManager());
        layoutView();
        initData();

    }

    private void layoutView() {
        backLeft = findViewById(R.id.back_left);
        tvPageName = findViewById(R.id.tv_page_name);
        ivHeadImage = findViewById(R.id.iv_head_image);
        tvInformationName = findViewById(R.id.tv_information_name);
        tvInformationNv = findViewById(R.id.tv_information_nv);
        tvInformationOld = findViewById(R.id.tv_information_old);
        tvInformationPhone = findViewById(R.id.tv_information_phone);
        btnLoginOut = findViewById(R.id.btn_loginout);
        rlInformationName = findViewById(R.id.rl_information_name);
        rlHeadImage = findViewById(R.id.rl_head_image);
        rlGender = findViewById(R.id.rl_gender);
        rlDataDialog = findViewById(R.id.rl_data_dialog);
    }

    private void initData() {
        tvPageName.setText("个人信息");

        String imageHead = (String) AppSharePreferenceMgr.get(this, GlobalConfig.USER_AVATAR, "");
        String name = SharePreference.getStringSpParams(this, Common.ISUSERNAME, Common.SIUSERNAME);
        String sex = SharePreference.getStringSpParams(this, Common.ISUSERSEX, Common.SIUSERSEX);
        String old = (String) AppSharePreferenceMgr.get(mContext, ConfigSps.USER_BIRTHDAY, "");
        String phone = SharePreference.getStringSpParams(this, Common.ISUSERPHONE, Common.SIUSERPHONE);
        if (Utils.isNotEmpty(imageHead)) {
            ImageDisplayUtil.showImageView(this, imageHead, (ivHeadImage));
        }
        if (Utils.isNotEmpty(name)) {
            tvInformationName.setText(name);
        }
        if (Utils.isNotEmpty(sex)) {

            String strSexGetTo;
            if (sex.equals("MAN")) {
                strSexGetTo = "男";
            } else if (sex.equals("WOMAN")) {
                strSexGetTo = "女";
            } else {
                strSexGetTo = "未设置";
            }
            tvInformationNv.setText(strSexGetTo);
        }
        if (Utils.isNotEmpty(old)) {
            tvInformationOld.setText(old);
        }
        if (Utils.isNotEmpty(phone)) {
            tvInformationPhone.setText(phone);
        }

        backLeft.setOnClickListener(this);
        btnLoginOut.setOnClickListener(this);
        rlInformationName.setOnClickListener(this);
        rlHeadImage.setOnClickListener(this);
        rlGender.setOnClickListener(this);
        rlDataDialog.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.back_left:
                finish();
                break;
            case R.id.btn_loginout:
                showLoginOutDialog();
                break;
            case R.id.rl_information_name:
                Intent intent = new Intent(this, EditNameActivity.class);
                startActivityForResult(intent, 1716);
                break;
            case R.id.rl_head_image:
                showDialog();
                break;
            case R.id.rl_gender:
                initPriorityEvent();
                break;
            case R.id.rl_data_dialog:
                String trim = tvInformationOld.getText().toString().trim();
                if (Utils.isNotEmpty(trim)) {
                    strTrim = trim;
                } else {
                    strTrim = "1990-01-01";
                }
                showDateDialog(DateUtil.INSTANCE.getCurDateStr());
                break;
            default:
                break;
        }
    }

    @Override
    public void setBgaAdpaterAndClickResult(UserInfoBean result) {

        setUserInfo(result);


    }

    private void setUserInfo(UserInfoBean result) {


        if (Utils.isNotEmpty(result.getData().getAvatar().getAccessUrl())) {

            ImageDisplayUtil.showImageView(this, result.getData().getAvatar().getAccessUrl(), ivHeadImage);
        }
        if (Utils.isNotEmpty(result.getData().getName())) {
            tvInformationName.setText(result.getData().getName());
        }
        if (Utils.isNotEmpty(result.getData().getSex())) {
            String str_sex_get;
            if (result.getData().getSex().equals("MAN")) {
                str_sex_get = "男";
            } else if (result.getData().getSex().equals("WOMAN")) {
                str_sex_get = "女";
            } else {
                str_sex_get = "未设置";
            }
            tvInformationNv.setText(str_sex_get);
        }
        if (Utils.isNotEmpty(result.getData().getBirthday())) {

            tvInformationOld.setText(TimerToTimerUtil.stampToInspectionDate(result.getData().getBirthday() + ""));
        }
        if (Utils.isNotEmpty(result.getData().getCompanyPhone())) {
            tvInformationPhone.setText(result.getData().getCompanyPhone());
        }

    }

    @Override
    public void setHeadImage(User result) {

    }

    @Override
    public void setSex(User result) {

    }

    @Override
    public void setData(User result) {

    }

    @Override
    public void setLogout(LogoutBean user) {
        if (user.getResponseCode() == 1001) {
            SharePreference.saveStringToSpParams(InformationActivity.this, Common.ISORNOLOGIN, Common.SIORNOLOGIN, "");
            finish();
        }
    }

    private void showLoginOutDialog() {
        final DialogLoginOut dialogLoginOut = new DialogLoginOut(InformationActivity.this, R.layout.item_dialog_loginout);
        dialogLoginOut.setTitle("你确定要退出账号吗？");
        dialogLoginOut.setMessage("退出账号后，您的信息将不会失去。但您将收不到关于您的任何通知信息。");
        dialogLoginOut.setYesOnclickListener("确认退出", new DialogLoginOut.OnPositiveOnclickListener() {
            @Override
            public void onYesClick() {
                userInformation = new UserInformationImpl(InformationActivity.this, "");
                userInformation.setLogout(InformationActivity.this);
                dialogLoginOut.dismiss();
            }
        });
        dialogLoginOut.setNoOnclickListener("取消", new DialogLoginOut.OnPassiveOnclickListener() {
            @Override
            public void onNoClick() {

                dialogLoginOut.dismiss();
            }
        });
        dialogLoginOut.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1716) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                String newName = bundle.getString("newName");
                tvInformationName.setText(newName);

            }
        }

        if (requestCode == RESULT_CODE) {
            if (null != data && null != (data.getExtras())) {
                // 通过Bundle获取data里面传输数据
                Bundle bundle = data.getExtras();
                // 转化数据
                Bitmap bitmap = (Bitmap) bundle.get("data");
                // 将图片添加到imagineview1中
                ivHeadImage.setImageBitmap(bitmap);
                try {
                    File headImage = saveFile(bitmap, "headImage");
                    sendImageHttp(headImage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
        if (requestCode == SAVE_CODE) {
            if (null != data) {
                // 加载本地库的图片
                final Uri uri = data.getData();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = null;
                        try {


                            bitmap = Glide
                                    .with(InformationActivity.this)
                                    .load(uri)
                                    .asBitmap()
                                    .centerCrop()
                                    .into(500, 500)
                                    .get();
                            bitmap1 = CompressionImageUtil.compressScale(bitmap);

                            File headImage = saveFile(bitmap1, "headImage");
                            sendImageHttp(headImage);
                            //子线程发送信息
                            Message msg = mHandler.obtainMessage(MSG_CODE);
                            msg.sendToTarget();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

        }
    }

    private void showDialog() {
        selfDialog = new PhotoAlbumDialog(InformationActivity.this, R.layout.photo_album_dialog_layout);
        selfDialog.setTitle("");
        selfDialog.setMessage("");
        selfDialog.setYesOnclickListener("拍照", new PhotoAlbumDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {


                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                startActivityForResult(intent, RESULT_CODE);

                selfDialog.dismiss();
            }
        });

        selfDialog.setYesAlbumOnclickListener("从本地选择", new PhotoAlbumDialog.onYesAlbumOnclickListener() {
            @Override
            public void onYesAlbumClick() {

                Intent intent1 = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent1.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                startActivityForResult(intent1, SAVE_CODE);

                selfDialog.dismiss();
            }
        });

        selfDialog.setNoOnclickListener("取消", new PhotoAlbumDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {

                selfDialog.dismiss();
            }
        });


        selfDialog.show();
    }

    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public File saveFile(Bitmap bm, String fileName) throws IOException {
        String path = getSDPath() + "/revoeye/";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName + ".jpg");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;
    }

    /**
     * 提交图片
     *
     * @param file
     */
    private void sendImageHttp(File file) {


        final String refreshToken = (String) AppSharePreferenceMgr.get(this, GlobalConfig.Refresh_token, "");
        String token = (String) AppSharePreferenceMgr.get(this, GlobalConfig.TOKEN, "");
        OkGo.<String>post(GlobalApi.INSTANCE.getUserImage())
                .params("access_token", token)
                .params("file", file)
                .isSpliceUrl(true)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        AvatarBean dataBean = JsonUtil.fromJson(response.body(), AvatarBean.class);

                        if (dataBean == null) {
                            return;
                        }
                        switch (dataBean.getResponseCode()) {
                            case 1001:
                                if (null != dataBean.getData() && null != dataBean.getData().getAvatar()) {

                                    AppSharePreferenceMgr.put(mContext, GlobalConfig.USER_AVATAR, dataBean.getData().getAvatar());
//                                    SharePreference.saveStringToSpParams(InformationActivity.this, Common.ISIMAGEHEAD, Common.SIIMAGEHEAD, responseEntity.getData().get(0).getAvatar());
                                }

                                break;
                            case 1018:
                                RefreshTokenUtil.refreshToken(InformationActivity.this, refreshToken);
                                break;
                            case 1019:
                                LoginOutUtil.sendLoginOutUtil(InformationActivity.this);
                                break;

                            default:
                                break;

                        }

                    }
                });
    }

    /**
     * 性别
     */
    private void initPriorityEvent() {
        final WheelPriorityDialogFragment wheelViewDialogFragment = WheelPriorityDialogFragment
                .newInstance(ResUtil.getStringArray(R.array.main_gender_menu),
                        ResUtil.getString(R.string.app_cancel),
                        ResUtil.getString(R.string.app_sure), true, false, true);
        wheelViewDialogFragment.setWheelDialogListener(new WheelPriorityDialogFragment.OnWheelDialogListener() {
            @Override
            public void onClickLeft(String value) {
                wheelViewDialogFragment.dismiss();
            }

            @Override
            public void onClickRight(String value) {
                wheelViewDialogFragment.dismiss();

                if (value.equals("男")) {
                    strSex = "MAN";
                    tvInformationNv.setText("男");
                    SharePreference.saveStringToSpParams(InformationActivity.this, Common.ISUSERSEX, Common.SIUSERSEX, "MAN");
                } else if (value.equals("女")) {
                    strSex = "WOMAN";
                    tvInformationNv.setText("女");
                    SharePreference.saveStringToSpParams(InformationActivity.this, Common.ISUSERSEX, Common.SIUSERSEX, "WOMAN");
                } else {
                    strSex = "NONE";
                    tvInformationNv.setText("未设置");
                }

                userInformation = new UserInformationImpl(InformationActivity.this, strSex);
                userInformation.setSex(InformationActivity.this);

            }

            @Override
            public void onAllcenter(String value) {


                wheelViewDialogFragment.dismiss();
            }

            @Override
            public void onValueChanged(String value) {
                Log.i("", "current value: " + value);
            }
        });
        wheelViewDialogFragment.show(getSupportFragmentManager(), "");

    }


    /**
     * 显示生日对话框
     *
     * @param date
     */

    private void showDateDialog(String date) {


        final DatePicker picker = new DatePicker(this);
        picker.setCanceledOnTouchOutside(true);
        picker.setUseWeight(true);
        picker.setTopLineColor(getResources().getColor(R.color.color_divider_0_1));
        picker.setCancelTextColor(getResources().getColor(R.color.black_text_80));
        picker.setSubmitTextColor(getResources().getColor(R.color.word_green));
        picker.setPressedTextColor(getResources().getColor(R.color.word_green));
        picker.setDividerColor(getResources().getColor(R.color.black_text_40));
        picker.setTextColor(getResources().getColor(R.color.black_text_80));
        picker.setTopPadding(ConvertUtils.toPx(this, 10));
        picker.setRangeEnd(2111, 1, 11);
        picker.setRangeStart(1800, 1, 1);
        picker.setSelectedItem(1990, 1, 1);
        picker.setResetWhileWheel(false);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                String userBirthday = (year + "-" + month + "-" + day);
                Log.e(BUG_TAG, userBirthday);

                modifyBirthday(userBirthday);
//                userInformation = new UserInformationImpl(InformationActivity.this, userBirthday);
//                userInformation.setData(InformationActivity.this);
            }
        });


        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });

        picker.show();
    }


    /**
     * 修改出生日期
     *
     * @param userBirthday
     */
    private void modifyBirthday(final String userBirthday) {


        final String strRefreshToken = (String) AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_REFRESH_TOKEN, "");
        HttpParams httpParams = new HttpParams();
        httpParams.put("birthday", userBirthday);

        mNetworkHelper.putRequestWithoutToken(GlobalApi.INSTANCE.getModify(), true, httpParams, new NetworkHelper.NetWorkHelperBack() {
            @Override
            public void requestSuccess(@NotNull String json) {
                BackEntity backEntity = JsonUtil.fromJson(json, BackEntity.class);


                if (backEntity.getResponseCode() == 1001) {
                    tvInformationOld.setText(userBirthday);
                    AppSharePreferenceMgr.put(mContext, ConfigSps.USER_BIRTHDAY, userBirthday);
                } else if (backEntity.getResponseCode() == 1018) {
                    RefreshTokenUtil.refreshToken(mContext, strRefreshToken);
                } else if (backEntity.getResponseCode() == 1019) {
                    LoginOutUtil.sendLoginOutUtil(mContext);
                }
            }

            @Override
            public void requestFail() {

            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
    }
}
